/*
 * Copyright (C) by Fluid Operations.
 * All rights reserved.
 *
 * For more information go to http://www.fluidops.com
 */

package com.fluidops.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import sun.nio.cs.StandardCharsets;

/**
 * @author stefan
 *
 */
public class FileHelper
{	
	public static List<File> getFilesRecursive(File basePath)
	{
		ArrayList<File> files = new ArrayList<File>();
		File[] children = basePath.listFiles();
		for(File f : children)
		{
			if(f.isDirectory())
				files.addAll(getFilesRecursive(f));
			else
				files.add(f);
		}
		return files;
	}

	public static void copyFile(String src, String des) throws IOException
	{
		copyFile(new File(src), new File(des));
	}
	
	public static void copyFile(File src, File des) throws IOException
	{
		FileInputStream in = null;
		FileOutputStream out = null;
		try
		{
			in = new FileInputStream(src);
			out = new FileOutputStream(des);
		
			byte[] buf = new byte[1024];
			int len = 0;
			while((len = in.read(buf)) > 0)
				out.write(buf, 0, len);
		}
		finally
		{
			if(in != null)
				in.close();
			if(out != null)
				out.close();
		}
	}
	
	public static void copyFiles(String[] src, String srcBasePath, String destPath) throws IOException
	{
		File[] srcFiles = new File[src.length];
		for(int i = 0; i < src.length; i++)
			srcFiles[i] = new File(src[i]);
		
		copyFiles(srcFiles, srcBasePath, destPath);
	}
	
	public static void copyFiles(File[] src, String srcBasePath, String destPath) throws IOException
	{
		for(File f : src)
		{
			String fileName;
	
			if(f.isAbsolute())
			{
				fileName = f.getAbsolutePath();
				if(fileName.startsWith(srcBasePath))
					fileName = destPath + fileName.substring(srcBasePath.length());
				else
					fileName = destPath + f.getName();
			}
			else
			{
				fileName = destPath + f.getPath();
				f = new File(srcBasePath + f.getPath());
			}
			
			File dest = new File(fileName);
			if(dest.getParentFile() != null && !dest.getParentFile().exists())
				dest.getParentFile().mkdirs();
			
			copyFile(f, dest);
		}
	}
}
